<template>
  <GlobalDrawer
    v-model="visible"
    :title="formTitle"
    size="80%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <!-- 客户选择 -->
      <el-form-item label="客户" prop="customer_id">
        <!-- 编辑模式或已有客户名称时显示只读文本 -->
        <div v-if="props.followupId || localCustomerName" style="width: 100%">
          <el-input v-model="localCustomerName" placeholder="客户" readonly style="width: 100%" />
        </div>
        <!-- 新增模式且没有客户名称时显示下拉选择 -->
        <div v-else style="width: 100%">
          <el-select
            v-model="form.customer_id"
            placeholder="请选择客户"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
      </el-form-item>

      <!-- 关联机会：选择0表示常规跟进，选择具体机会ID表示机会跟进 -->
      <el-form-item label="关联机会" prop="opportunity_id">
        <el-select
          v-model="form.opportunity_id"
          placeholder="请选择要跟进的销售机会（不选择表示常规跟进）"
          filterable
          clearable
          style="width: 100%"
          :loading="opportunityLoading"
          @change="handleOpportunityChange"
        >
          <el-option :key="0" label="不关联机会 - 常规跟进" :value="0" />
          <el-option
            v-for="item in opportunityOptions"
            :key="item.id"
            :label="`${item.title} [${getOpportunityLevelText(item.level)}]`"
            :value="item.id"
          />
        </el-select>
        <div style="margin-top: 8px; color: #909399; font-size: 12px">
          <el-icon><InfoFilled /></el-icon>
          选择"不关联机会"表示常规跟进，选择具体机会表示机会跟进
        </div>
      </el-form-item>

      <el-form-item label="跟进类型" prop="followup_type">
        <el-select v-model="form.followup_type" placeholder="请选择跟进类型" style="width: 100%">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跟进时间" prop="followup_time">
        <el-date-picker
          v-model="form.followup_time"
          type="datetime"
          placeholder="请选择跟进时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="跟进内容" prop="content">
        <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入跟进内容" />
      </el-form-item>

      <el-form-item label="下次跟进">
        <el-date-picker
          v-model="form.next_followup_time"
          type="datetime"
          placeholder="请选择下次跟进时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
/* eslint-env vue */
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { InfoFilled } from '@element-plus/icons-vue'
  import axios, { CancelTokenSource } from 'axios'
  import followupApi from '@/api/crm/followup'
  import { customerApi } from '@/api/crm'
  import opportunityApi from '@/api/crm/opportunity'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  // 类型定义
  interface CustomerOption {
    id: number
    name: string
  }

  interface TypeOption {
    value: number
    label: string
  }

  interface OpportunityOption {
    id: number
    title: string
    level: number
  }

  interface FollowupFormData {
    customer_id: number
    customer_name: string
    followup_type: number
    followup_time: string
    content: string
    next_followup_time: string
    opportunity_id: number
  }

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    followupId: {
      type: Number,
      default: 0,
    },
    customerId: {
      type: Number,
      default: 0,
    },
    customerName: {
      type: String,
      default: '',
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  // 简化的可见状态控制，避免递归更新
  const visible = ref(props.modelValue)
  
  // 监听外部 modelValue 变化
  watch(() => props.modelValue, (newVal) => {
    visible.value = newVal
  })
  
  // 监听内部 visible 变化，避免无限递归
  watch(visible, (newVal, oldVal) => {
    if (newVal !== oldVal && newVal !== props.modelValue) {
      emit('update:modelValue', newVal)
    }
  })

  const formRef = ref<FormInstance | null>(null)
  const loading = ref(false)
  const submitting = ref(false)
  let cancelToken: CancelTokenSource | null = null

  const form = reactive({
  // 表单数据结构
    customer_id: 0,
    customer_name: '', // 客户名称（从客户列表发起时显示）
    followup_type: 1, // 默认选择第一个跟进类型
    followup_time: '', // 默认空，用户必须选择
    content: '', // 默认空，用户必须填写
    next_followup_time: '', // 可选字段
    opportunity_id: 0, // 0-常规跟进（不关联机会），>0-机会跟进（关联具体机会）
  })

  // 本地客户名称副本（避免直接修改 props）
  const localCustomerName = ref('')

  // 监听 customerName 变化，更新本地客户名称
  watch(
    () => props.customerName,
    newVal => {
      if (newVal && newVal !== localCustomerName.value) {
        localCustomerName.value = newVal
      }
    },
    { immediate: true }
  )

  const rules = {
    customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
    followup_type: [{ required: true, message: '请选择跟进类型', trigger: 'change' }],
    followup_time: [{ required: true, message: '请选择跟进时间', trigger: 'change' }],
    content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }],
  }

  // 移除TypeScript类型定义，使用纯JavaScript

  // 客户选项
  const customerOptions = ref<CustomerOption[]>([])
  // 类型选项
  const typeOptions = ref<TypeOption[]>([])
  // 机会选项
  const opportunityOptions = ref<OpportunityOption[]>([])
  const opportunityLoading = ref(false)

  // 获取机会等级文本
  const getOpportunityLevelText = (level: number): string => {
    const levelMap: Record<number, string> = {
      1: 'A级',
      2: 'B级',
      3: 'C级',
    }
    return levelMap[level] || '未知'
  }

  // 表单标题
  const formTitle = computed(() => {
    return props.followupId ? '编辑跟进' : '新增跟进'
  })

  // 处理关联机会变化
  const handleOpportunityChange = (value: number) => {
    // 0表示常规跟进，其他值表示机会跟进
    // 已在表单中通过UI提示
  }

  // 获取客户下的有效机会列表
  const getOpportunityList = async (customerId: number): Promise<void> => {
    if (!customerId) {
      console.warn('⚠️ getOpportunityList: customerId为空，不获取机会列表')
      return
    }

    console.log('🔍 开始获取机会列表，customerId:', customerId)
    opportunityLoading.value = true
    try {
      // 调用机会API，获取该客户下所有状态的机会（暂时移除status限制以便调试）
      const params = {
        customer_id: customerId,
        // status: 1, // 暂时移除状态限制，获取所有状态的机会
        limit: 100, // 获取更多数据
      }
      console.log('🔍 请求参数:', params)

      const res = await opportunityApi.getOpportunityList(params)
      console.log('🔍 API原始响应:', res)

      if (res.data.code === 0) {
        const list = res.data.data.list || []
        console.log('✅ 获取到机会列表，数量:', list.length, '列表:', list)
        opportunityOptions.value = list
      } else {
        console.warn('⚠️ API返回错误，code:', res.data.code, 'message:', res.data.message)
      }
    } catch (error: any) {
      // 忽略取消请求的错误和其他非致命错误
      const errorCode = error?.code
      const errorMessage = error?.message

      // 如果是取消请求、网络错误或400错误，不显示错误提示（这些不是致命错误）
      if (
        errorCode === 'ERR_CANCELED' ||
        errorCode === 'ERR_NETWORK' ||
        errorCode === 'ERR_BAD_REQUEST' ||
        errorMessage?.includes('canceled') ||
        errorMessage?.includes('cancelled')
      ) {
        console.log('机会列表请求被取消或网络错误，已忽略:', errorMessage)
        return
      }

      // 只有真正的服务器错误才显示错误提示
      console.error('获取机会列表失败:', error)
      ElMessage.error('获取机会列表失败，请稍后重试')
    } finally {
      opportunityLoading.value = false
    }
  }

  // 获取跟进详情
  const getFollowupDetail = async (): Promise<void> => {
    if (!props.followupId) {
      console.warn('没有跟进ID，不获取详情')
      return
    }

    console.log('开始获取跟进详情, ID:', props.followupId)
    loading.value = true

    try {
      // 创建新的取消令牌
      cancelToken = axios.CancelToken.source()

      // 调用API并传递取消令牌
      console.log('发送API请求, ID:', props.followupId)
      const res = await followupApi.detail(props.followupId)
      const data = res.data

      console.log('✅ API返回的原始数据:', JSON.stringify(data, null, 2))
      console.log('✅ 跟进详情数据字段:', Object.keys(data))
      console.log('✅ 跟进详情数据完整内容:', data)

      // 编辑模式下，设置客户名称为只读显示
      if (data.customer_name) {
        localCustomerName.value = data.customer_name
        console.log('✅ 设置客户名称:', localCustomerName.value)
      } else {
        console.warn('⚠️ 没有客户名称数据')
      }

      // 重置表单数据
      console.log('📝 重置表单数据...')
      Object.assign(form, {
        customer_id: 0,
        customer_name: '',
        followup_type: 1,
        followup_time: '',
        content: '',
        next_followup_time: '',
        opportunity_id: 0,
      })

      // 手动映射并填充表单数据
      console.log('📝 开始填充表单数据...')

      // 1. 客户ID
      console.log('🔍 检查客户ID字段 - data.customer_id:', data.customer_id, typeof data.customer_id)
      console.log('🔍 检查所有可能字段 - data:', Object.keys(data).filter(k => k.includes('customer')))
      if (data.customer_id !== undefined && data.customer_id !== null && data.customer_id !== 0) {
        form.customer_id = Number(data.customer_id)
        console.log('✅ 设置客户ID:', form.customer_id)
      } else {
        console.warn('⚠️ 客户ID无效，跳过设置. 原始值:', data.customer_id)
      }

      // 2. 跟进类型
      if (data.followup_type !== undefined) {
        form.followup_type = Number(data.followup_type)
        console.log('✅ 设置跟进类型:', form.followup_type)
      }

      // 3. 跟进时间（时间戳转换）
      if (data.followup_time) {
        const followTimeValue = data.followup_time
        console.log('原始跟进时间值:', followTimeValue, typeof followTimeValue)
        if (typeof followTimeValue === 'number' && followTimeValue > 0) {
          // 处理秒级时间戳
          const date = new Date(followTimeValue * 1000)
          form.followup_time = formatDateTime(date)
          console.log('✅ 转换跟进时间:', form.followup_time)
        } else {
          form.followup_time = ''
          console.warn('⚠️ 跟进时间格式无效:', followTimeValue)
        }
      } else {
        form.followup_time = ''
        console.warn('⚠️ 没有跟进时间数据')
      }

      // 4. 跟进内容
      if (data.content !== undefined) {
        form.content = data.content || ''
        console.log('✅ 设置跟进内容:', form.content)
      }

      // 5. 下次跟进时间（时间戳转换）
      if (data.next_followup_time) {
        const nextTimeValue = data.next_followup_time
        console.log('原始下次跟进时间值:', nextTimeValue, typeof nextTimeValue)
        if (typeof nextTimeValue === 'number' && nextTimeValue > 0) {
          // 处理秒级时间戳
          const date = new Date(nextTimeValue * 1000)
          form.next_followup_time = formatDateTime(date)
          console.log('✅ 转换下次跟进时间:', form.next_followup_time)
        } else {
          form.next_followup_time = ''
          console.warn('⚠️ 下次跟进时间格式无效:', nextTimeValue)
        }
      } else {
        form.next_followup_time = ''
        console.warn('⚠️ 没有下次跟进时间数据')
      }

      // 6. 关联机会ID
      if (data.opportunity_id !== undefined) {
        form.opportunity_id = Number(data.opportunity_id)
        console.log('✅ 设置机会ID:', form.opportunity_id)
      }

      console.log('✅ 最终填充的表单数据:', JSON.stringify(form, null, 2))

      // 加载关联的机会列表（如果有客户ID）
      if (form.customer_id) {
        console.log('加载客户机会列表, customerId:', form.customer_id)
        await getOpportunityList(form.customer_id)
      } else {
        console.warn('⚠️ 没有客户ID，不加载机会列表')
      }
    } catch (error) {
      // 忽略取消请求的错误
      if (!axios.isCancel(error)) {
        console.error('❌ 获取跟进详情失败:', error)
        ElMessage.error('获取跟进详情失败，请重试')
      }
    } finally {
      loading.value = false
      console.log('✅ 数据加载完成，loading设置为false')
    }
  }

  // 辅助函数：格式化日期时间为YYYY-MM-DD HH:mm:ss格式
  const formatDateTime = (date: Date): string => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 获取选项数据
  const getOptions = async (): Promise<void> => {
    try {
      const [customerRes, typeRes] = await Promise.all([
        customerApi.getCustomerOptions(),
        followupApi.getFollowupTypeOptions(),
      ])
      customerOptions.value = customerRes.data.map(
        (item: { value: string | number; label: string }) => ({
          id: Number(item.value),
          name: item.label,
        })
      )
      // 从API获取跟进类型选项
      typeOptions.value = (typeRes.data || []).filter(
        (item) => item && item.value !== undefined && item.value !== null
      )
      console.log('跟进类型选项:', typeOptions.value)
    } catch (error) {
      console.error('获取选项失败:', error)
      // 设置默认的跟进类型选项
      typeOptions.value = [
        { value: 1, label: '电话联系' },
        { value: 2, label: '微信沟通' },
        { value: 3, label: '邀约到场' },
        { value: 4, label: '上门拜访' }
      ]
    }
  }

  // 提交表单
  const handleSubmit = async (): Promise<void> => {
    if (!formRef.value) return

    // 验证表单
    try {
      const validationResult = await formRef.value.validate()
      
      // 如果验证失败，validationResult 为 false
      if (validationResult === false) {
        ElMessage.error('请填写完整的表单信息')
        return
      }

      submitting.value = true

      // 处理表单数据，包含customer_name
      const submitData = {
        customer_id: props.customerId || form.customer_id,
        customer_name: props.customerName || form.customer_name,
        followup_type: form.followup_type,
        followup_time: form.followup_time,
        content: form.content,
        next_followup_time: form.next_followup_time,
        opportunity_id: form.opportunity_id,
        user_id: 1,
      }

      if (props.followupId) {
        await followupApi.edit({ ...submitData, id: props.followupId })
        ElMessage.success('编辑成功')
      } else {
        await followupApi.create(submitData)
        ElMessage.success('新增成功')
      }

      emit('success')
      handleClose()
    } catch (error: any) {
      console.error('提交失败:', error)
      
      // 处理表单验证错误
      if (error && typeof error === 'object') {
        const validationErrors: string[] = []
        
        // 提取验证错误信息
        Object.keys(error).forEach(field => {
          if (error[field] && Array.isArray(error[field])) {
            error[field].forEach((msg: string) => {
              validationErrors.push(msg)
            })
          }
        })
        
        if (validationErrors.length > 0) {
          ElMessage.error(`表单验证失败：${validationErrors.join(', ')}`)
        } else {
          ElMessage.error('表单验证失败，请检查必填字段')
        }
      } else {
        ElMessage.error('提交失败，请稍后重试')
      }
    } finally {
      submitting.value = false
    }
  }

  // 关闭对话框
  const handleClose = (): void => {
    // 取消所有待处理的请求
    if (cancelToken) {
      cancelToken.cancel('Dialog closed')
      cancelToken = null
    }
    
    // 先重置表单字段状态
    if (formRef.value) {
      formRef.value.resetFields()
    }
    
    // 批量重置表单字段为初始状态
    Object.assign(form, {
      customer_id: 0,
      customer_name: '',
      followup_type: 1, // 重置为默认值
      followup_time: '', // 清空必填字段
      content: '', // 清空必填字段  
      next_followup_time: '', // 清空可选字段
      opportunity_id: 0,
    })
    
    // 清空选项数据
    opportunityOptions.value = []
    localCustomerName.value = ''

    // 关闭对话框
    visible.value = false
  }

  // 监听客户ID变化，重新获取机会列表
  watch(
    () => form.customer_id,
    (newVal: number | null, oldVal: number | null) => {
      if (newVal && newVal !== oldVal && newVal > 0) {
        console.log('客户ID变化，加载机会列表:', newVal)
        // 延迟执行，避免快速变化导致的请求过多
        setTimeout(() => {
          getOpportunityList(newVal)
        }, 100)
      }
    }
  )

  // 监听props.customerId变化（在从客户列表进入时触发）
  watch(
    () => props.customerId,
    (newVal: number) => {
      console.log('props.customerId变化:', newVal)
      if (newVal && newVal !== form.customer_id) {
        form.customer_id = newVal
      }
    },
    { immediate: true }
  )

  // 监听抽屉打开
  watch(visible, (newVisible) => {
    if (newVisible) {
      console.log('抽屉打开，开始初始化数据...')
      // 使用 setTimeout 延迟执行，确保 DOM 更新完成
      setTimeout(async () => {
        try {
          // 获取选项数据
          await getOptions()

          // 编辑模式：获取跟进详情
          if (props.followupId) {
            console.log('编辑模式，获取跟进详情:', props.followupId)
            await getFollowupDetail()
          }
          // 新增模式：初始化表单
          else {
            console.log('新增模式，初始化表单，customerId:', props.customerId)

            // 从props获取customerId
            if (props.customerId) {
              form.customer_id = props.customerId
              // 加载机会列表
              await getOpportunityList(props.customerId)
            }

            // 设置默认跟进时间为当前时间
            const now = new Date()
            form.followup_time = formatDateTime(now)

            console.log('新增模式下表单初始化完成:', form)
          }
        } catch (error) {
          console.error('数据加载失败:', error)
        }
      }, 100)
    } else {
      // 抽屉关闭时取消请求
      if (cancelToken) {
        cancelToken.cancel('Dialog closed')
        cancelToken = null
      }
    }
  }, { immediate: true })

  // 监听followupId变化
  watch(() => props.followupId, async (newId) => {
    // 当抽屉已打开且followupId变化时，重新加载数据
    if (visible.value && newId) {
      console.log('followupId变化，重新加载数据:', newId)
      try {
        await getFollowupDetail()
      } catch (error) {
        console.error('重新加载数据失败:', error)
      }
    }
  })

  // 暴露给父组件的方法和属性
  defineExpose({
    handleClose,
  })
</script>

<style scoped>
  .el-form {
    padding-right: 20px;
  }
</style>
